﻿
//中断处理类
//格式: 中断地址 + 空格 + 函数序号 + 空格 + 错误定位索引 + \n + ...
namespace n_Interrupt
{
using System;

public static class Interrupt
{
	//注意这里本来定义的150, 后来合并 base code 之后不行了, 找了半天终于发现是这的问题
	//public const int StaceSize = 200;
	
	//清除中断序列
	public static void Reset( int ChipNumber )
	{
		ChipIndex = -1;
		
		IntSet = new string[ ChipNumber ];
		TatolStackNumber = new int[ ChipNumber ];
		
		StartAddrOfBaseCode = 0;
		
		for( int i = 0; i < ChipNumber; ++i ) {
			IntSet[ i ] = null;
			TatolStackNumber[ i ] = 0;
		}
	}
	
	//设置当前芯片序号
	public static void SetChipIndex( int Index )
	{
		ChipIndex = Index;
	}
	
	//判断中断入口地址是否被占用
	public static bool isUsed( int Addr )
	{
		if( IntSet[ ChipIndex ] == null ) {
			return false;
		}
		string[] Cut = IntSet[ ChipIndex ].TrimEnd( '\n' ).Split( '\n' );
		for( int i = 0; i < Cut.Length; ++i ) {
			if( Cut[ i ].StartsWith( Addr + " " ) ) {
				return true;
			}
		}
		return false;
	}
	
	//添加中断入口
	public static void Add( string IntAddr )
	{
		IntSet[ ChipIndex ] += IntAddr + "\n";
	}
	
	//显示
	public static string Show()
	{
		return string.Join( "\n--------\n", IntSet );
	}
	
	//获取中断入口集合
	public static string[] GetSet()
	{
		if( IntSet[ ChipIndex ] == null ) {
			return null;
		}
		string[] Cut = IntSet[ ChipIndex ].TrimEnd( '\n' ).Split( '\n' );
		
		//按照从小到大的顺序排序
		for( int i = 0; i < Cut.Length - 1; ++i ) {
			int i_Number = int.Parse( Cut[ i ].Split( ' ' )[ 0 ] );
			for( int j = i + 1; j < Cut.Length; ++j ) {
				int j_Number = int.Parse( Cut[ j ].Split( ' ' )[ 0 ] );
				if( j_Number < i_Number ) {
					string Copy = Cut[ j ];
					Cut[ j ] = Cut[ i ];
					Cut[ i ] = Copy;
					i_Number = j_Number;
				}
			}
		}
		return Cut;
	}
	
	//增加堆栈数目
	public static void AddStackNumber( int Number )
	{
		if( Number > MaxNumber ) {
			Number = MaxNumber;
		}
		TatolStackNumber[ ChipIndex ] += Number;
	}
	
	//获取中断函数占据的堆栈数目
	public static int GetStackNumber()
	{
		return TatolStackNumber[ ChipIndex ];
	}
	
	//8个字节的接口变量起始地址, 需要在中断中保存这些数据, 防止中断中再次调用引用接口的冲突
	public static int StartAddrOfBaseCode;
	
	//中断入口集合
	static string[] IntSet;
	static int[] TatolStackNumber;
	static int ChipIndex;
	
	public static int MaxNumber = 200;
	public const int C_MaxNumber = 200;
}
}
